import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;


public class KeyboardController
{
	private Toolkit toolKit = null;
	private Robot robot = null;

	private boolean isCapsLock = false;
	private boolean isNumLock = false;
	private boolean isScrollLock = false;

	public KeyboardController() throws AWTException 
	{
		toolKit = Toolkit.getDefaultToolkit () ;
		robot = new Robot();
		chkLockingKeyState();
	}

	private void chkLockingKeyState()
	{
		isCapsLock = toolKit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
		isNumLock = toolKit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
		isScrollLock = toolKit.getLockingKeyState(KeyEvent.VK_SCROLL_LOCK);
	}

	private void setCapsLock()
	{
		if(isCapsLock)
		{
			isCapsLock = false;
			toolKit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, false);
		}
		else
		{
			isCapsLock = true;
			toolKit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
		}
	}

	private void setNumLock()
	{
		if(isNumLock)
		{
			isNumLock = false;
			toolKit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, false);
		}
		else
		{
			isNumLock = true;
			toolKit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, true);
		}
	}

	private void setScrollLock()
	{
		if(isScrollLock)
		{
			isScrollLock = false;
			toolKit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, false);
		}
		else
		{
			isScrollLock = true;
			toolKit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, true);
		}
	}

	public void controlKey(int keycode, boolean press)
	{

		switch (keycode) 
		{

		case KeyEvent.VK_CAPS_LOCK:
			if(press)
			{
				setCapsLock();
			}
			break;

		case KeyEvent.VK_NUM_LOCK:
			if(press)
			{
				setNumLock();
			}
			break;

		case KeyEvent.VK_SCROLL_LOCK:
			if(press)
			{
				setScrollLock();
			}
			break;

		default:
			if(press)
			{
				robot.keyPress(keycode);
			}
			else
			{
				robot.keyRelease(keycode);
			}
			break;
			
		}
	}
}
